//
//  MTSearchFriendResultViewController.swift
//  MT
//
//  Created by ooops on 2020/5/11.
//  Copyright © 2020 张强. All rights reserved.
//
import UIKit
import YPNavigationBarTransition

enum SearchFriendResultTypeEnum {
    ///
    case header
    /// 备注 / 标签
    case remarkOrTag
    /// 个性签名
    case singleSign
    /// 来源
    case from
    /// 添加好友
    case addContacter
}

public struct SearchFriendResultItemStruct {
    var itemName: String
    var isShowArrow: Bool
    var type: SearchFriendResultTypeEnum
    
    mutating func create(itemName: String, isShowArrow: Bool, type: SearchFriendResultTypeEnum) -> SearchFriendResultItemStruct {
        self.itemName = itemName
        self.isShowArrow = isShowArrow
        self.type = type
        return self
    }
}

class MTSearchFriendResultViewController: BaseViewController {
    private var giftView: MiTuGiftView?
//    var user: JMSGUser!
    fileprivate lazy var provider: MTProvider<MiTuGiftApi> = {
        return MTProvider<MiTuGiftApi>(plugins: [])
    }()
    var dataSource: [[SearchFriendResultItemStruct]] = [[]]
    
    private let clubProvider: MTProvider = MTProvider<MTClubApi>()
    
    var userModel: MTSearchUserInfoModel? {
        didSet {
            if let m = userModel, let isFriend = m.isFriend, isFriend {
                dataSource = [[SearchFriendResultItemStruct(itemName: "", isShowArrow: false, type: .header),
                 SearchFriendResultItemStruct(itemName: "备注", isShowArrow: true, type: .remarkOrTag)],
                [SearchFriendResultItemStruct(itemName: "个性签名", isShowArrow: false, type: .singleSign)/*,
                 SearchFriendResultItemStruct(itemName: "来源", isShowArrow: false, type: .from)*/],
                [SearchFriendResultItemStruct(itemName: "添加好友", isShowArrow: false, type: .addContacter)]]
            } else {
                dataSource = [[SearchFriendResultItemStruct(itemName: "", isShowArrow: false, type: .header)],
                [SearchFriendResultItemStruct(itemName: "个性签名", isShowArrow: false, type: .singleSign)/*,
                 SearchFriendResultItemStruct(itemName: "来源", isShowArrow: false, type: .from)*/],
                [SearchFriendResultItemStruct(itemName: "添加好友", isShowArrow: false, type: .addContacter)]]
            }
            self.tableView.reloadData()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        giftView?.removeFromSuperview()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        giftView?.removeFromSuperview()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    

    lazy var tableView: UITableView = {
        let table = UITableView(frame: view.bounds, style: .grouped)
        table.delegate = self
        table.dataSource = self
        table.register(MTSearchFriendResultCell.self, forCellReuseIdentifier: MTSearchFriendResultCell.reuseIdentity())
        table.register(MTSearchFriendResultHeaderCell.self, forCellReuseIdentifier: MTSearchFriendResultHeaderCell.reuseIdentity())
        table.register(MTSearchFriendAddCell.self, forCellReuseIdentifier: MTSearchFriendAddCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.sectionFooterHeight = 0
        table.sectionHeaderHeight = 0
        return table
    }()

}


extension MTSearchFriendResultViewController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data: SearchFriendResultItemStruct = self.dataSource[indexPath.section][indexPath.row]
        switch data.type {
        case .header:
            let cell = tableView.dequeueReusableCell(withIdentifier: MTSearchFriendResultHeaderCell.reuseIdentity(), for: indexPath) as! MTSearchFriendResultHeaderCell
            //cell.user = user
            cell.userModel = userModel
            //cell.showLine(long: true)
            return cell
        case .addContacter:
            let cell: MTSearchFriendAddCell = tableView.dequeueReusableCell(withIdentifier: MTSearchFriendAddCell.reuseIdentity(), for: indexPath) as! MTSearchFriendAddCell
            //cell.exLayout()
            //configureCell(cell: cell, forRowAt: indexPath)
            //cell.user = user
            cell.delegate = self
            return cell
        case .singleSign:
            let cell = tableView.dequeueReusableCell(withIdentifier: MTSearchFriendResultCell.reuseIdentity(), for: indexPath) as! MTSearchFriendResultCell
            configureCell(cell: cell, forRowAt: indexPath)
            //cell.user = user
            //cell.userModel = userModel
            //cell.showLine(long: true)
            cell.userModel = userModel
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: MTSearchFriendResultCell.reuseIdentity(), for: indexPath) as! MTSearchFriendResultCell
            cell.bindData(data: data)
            //cell.user = user
            //cell.userModel = userModel
            configureCell(cell: cell, forRowAt: indexPath)
            return cell
        }
    }
    
    func configureCell(cell: MTSearchFriendResultCell, forRowAt indexPath: IndexPath) {
        let data: SearchFriendResultItemStruct = self.dataSource[indexPath.section][indexPath.row]
        
        cell.bindData(data: data)
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data: SearchFriendResultItemStruct = self.dataSource[indexPath.section][indexPath.row]
        switch data.type {
        case .remarkOrTag:
            if let un = userModel?.userName {
                JMSGUser.userInfoArray(withUsernameArray: [un]) { (result, error) in
                    if error == nil {
                        let users = result as! [JMSGUser]
                        let user = users.first
                        let vc = MTEditFriendRemarkNameViewController()
                        vc.user = user
                        let nav = BaseNavController(rootViewController: vc)
                        nav.modalPresentationStyle = .fullScreen
                        nav.modalTransitionStyle = .crossDissolve
                        self.navigationController?.present(nav, animated: true, completion: nil)
                    }
                }
            }
            break
        default:
            break
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //return 64
        let data: SearchFriendResultItemStruct = self.dataSource[indexPath.section][indexPath.row]
        switch data.type {
        case .header:
            return 120
        default:
            return 54
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

extension MTSearchFriendResultViewController: MTSearchFriendAddCellDelegate {
    
//    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
//        return [.backgroundStyleColor, .backgroundStyleOpaque]
//    }
    func didClickedAddFriendButton(sender: UIButton) {
//        let vc = MTAddFriendViewController()
        if let un = userModel?.userName {
            
            giftView = self.presentGiftView(isFriend: false, imUserName: un, didClickRechargeCallBack: { [weak self] in
                guard let weakself = self else { return }
                if UserDefaults.AppValidate.isValidate.storedBool == false {
                    let c = MTPaymentViewController()
                    weakself.navigationController?.pushViewController(c, animated: true)
                } else {
                    let c = MTInAppPurchasesViewController()
                    weakself.navigationController?.pushViewController(c, animated: true)
                }
                }, selectedGiftCallBack: { [weak self] (model, count) in
                    guard let weakself = self else { return }
                    let c = MTAddFriendViewController(giftCount: count, targetUserName: un, giftModel: model)
                    weakself.navigationController?.pushViewController(c, animated: true)
            }, didClickSayHiCallBack: { [weak self] (model, count) in
                guard let weakself = self else { return }
                let c = MTAddFriendViewController(giftCount: count, targetUserName: un, giftModel: model)
                weakself.navigationController?.pushViewController(c, animated: true)
            }) {
                
            }
        }
    }
    
    @objc func _addFriend() {
        guard let userName = userModel?.userName else {
            return
        }
        
        let currentUser = JMSGUser.myInfo()
        if currentUser.username.isEmpty {
            NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil, userInfo: nil)
            return
        }
        
        JMSGFriendManager.sendInvitationRequest(withUsername: userName, appKey: nil, reason: "请求添加好友") { (result, error) in
            if error == nil {
                let currentUser = JMSGUser.myInfo()
                let info = JCVerificationInfo.create(username: userName, nickname: self.userModel?.nickname!, appkey: currentUser.appKey!, resaon: "请求添加好友", state: JCVerificationType.wait.rawValue, initiator: currentUser.username, type: .single, eventId: "")
                JCVerificationInfoDB.shareInstance.insertData(info)
                NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
                //MBProgressHUD_JChat.show(text: "好友请求已发送, 等待对方通过验证", view: self.view, 2)
//                weak var weakSelf = self
//                let time: TimeInterval = 2
//                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
//                    weakSelf?.navigationController?.popViewController(animated: true)
//                }
                let dict: [String: Any] = ["isSuccess": error == nil]
                NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionAddFriend.name, object: nil, userInfo: dict)
            }
//            else {
//                if let er = error as NSError?, er.code == 805002 {
//                    MBProgressHUD_JChat.show(text: "对方已经是你的好友", view: self.view, 2)
//                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
//                        self.navigationController?.popViewController(animated: true)
//                    }
//                }
//            }
        }
    }
    
    //@objc private func sendGift(giftModel: MiTuGiftModel, count: Int?) {
    private func sendGift(giftModel: MiTuGiftModel, count: Int?) {
        guard let count: Int = count else { return }
        guard let price = giftModel.price else { return }
        
        /// 查询创建俱乐部所需要消耗的钻石
        MTClubTool.config(provider: clubProvider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            let amount = price * count
            guard let ticketAmount = model?.result?.ticketAmount else { return }
            if model?.code == 200, price * count > ticketAmount {
                UIAlertController.rx.show(in: weakSelf, title: "余额不足", message: "此次将花费\(amount)钻石", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                    /// 去充值的引导
                    if index == 1 {
                        if UserDefaults.AppValidate.isValidate.storedBool == false {
                            let c = MTPaymentViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        } else {
                            let c = MTInAppPurchasesViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        }
                    }
                }).disposed(by: globalDisposedBag)
            } else {
                if let giftId = giftModel.id {
                    weakSelf._sendGift(count: count, giftId: giftId)
                }
            }
        }) { [weak self] (error) in
            guard let weakSelf = self else { return }
            MBProgressHUD_JChat.show(text: "网络异常", view: weakSelf.view)
            return
        }
    }
    
    private func _sendGift(count: Int, giftId: Int) {
        guard let userName = userModel?.userName else { return }
        let requestParam: [String : Any] = ["count": count,
                                            "giftId": giftId,
                                            "message": "",
                                            "userName": userName]
        
        provider.originRequest(.sendGift(requestParam), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
            guard let weakSelf = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200 {
                        if let result = datas["result"] as? [String: Any] {
                            UserCenter.default.set(with: result)
                        }
                        weakSelf._addFriend()
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: "好友请求已发送", view: weakSelf.view, 1)
                            DispatchQueue.main.after(1.1) {
                                weakSelf.navigationController?.popToRootViewController(animated: false)
                            }
                        }
                    } else if code == 600 {
                        // 600 余额不做
                        //weakSelf.presentFailAlert()
                        UIAlertController.rx.show(in: weakSelf, title: "余额不足", message: "是否进行充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                            /// 去充值的引导
                            if index == 1 {
                                if UserDefaults.AppValidate.isValidate.storedBool == false {
                                    let c = MTPaymentViewController()
                                    weakSelf.navigationController?.pushViewController(c, animated: true)
                                } else {
                                    let c = MTInAppPurchasesViewController()
                                    weakSelf.navigationController?.pushViewController(c, animated: true)
                                }
                            }
                        }).disposed(by: globalDisposedBag)
                    } else {
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
                    }
                }
                break
                
            case .failure(_):
                DispatchQueue.main.sync {
                    MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
                }
                break
            }
        }
    }
    
//    private func sendGift(giftModel: MiTuGiftModel, count: Int?) {
//        guard let count: Int = count else { return }
//        guard let price = giftModel.price else { return }
//        if price * count > UserDefaults.MTUserCenter.money.storedInt {
//            let amount = price * count
//            UIAlertController.rx.show(in: self, title: "余额不足", message: "此次将花费\(amount)钻石", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
//                /// 去充值的引导
//                if index == 1 {
//                    if UserDefaults.AppValidate.isValidate.storedBool == false {
//                        let c = MTPaymentViewController()
//                        self.navigationController?.pushViewController(c, animated: true)
//                    } else {
//                        let c = MTInAppPurchasesViewController()
//                        self.navigationController?.pushViewController(c, animated: true)
//                    }
//                }
//            })
//            .disposed(by: globalDisposedBag)
//            return
//        }
//
//        guard let userName = userModel?.userName else { return }
//        let requestParam: [String : Any] = ["count": count,
//                                            "giftId": giftModel.id!,
//                                            "message": "送礼啦",
//                                            "userName": userName]
//
//        provider.originRequest(.sendGift(requestParam), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
//            guard let weakSelf = self else { return }
//            switch result {
//            case let .success(response):
//                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
//
//                    if code == 200 {
//                        if let result = datas["result"] as? [String: Any] {
//                            UserCenter.default.set(with: result)
//                        }
//                        weakSelf._addFriend()
//                        DispatchQueue.main.async {
//                            MBProgressHUD_JChat.show(text: "好友请求已发送", view: weakSelf.view, 1)
//                            DispatchQueue.main.after(1.1) {
//                                weakSelf.navigationController?.popToRootViewController(animated: false)
//                            }
//                        }
//                    } else if code == 600 {
//                        // 600 余额不做
//                        //weakSelf.presentFailAlert()
//                        if UserDefaults.AppValidate.isValidate.storedBool == false {
//                            let c = MTPaymentViewController()
//                            weakSelf.navigationController?.pushViewController(c, animated: true)
//                        } else {
//                            let c = MTInAppPurchasesViewController()
//                            weakSelf.navigationController?.pushViewController(c, animated: true)
//                        }
//                    } else {
//                        DispatchQueue.main.async {
//                            MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
//                        }
//                    }
//                } else {
//                    DispatchQueue.main.async {
//                        MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
//                    }
//                }
//                break
//
//            case .failure(_):
//                DispatchQueue.main.sync {
//                    MBProgressHUD_JChat.show(text: "好友请求发送失败", view: weakSelf.view, 1)
//                }
//                break
//            }
//        }
//
//    }
    
}

